/*
 * @Description 
 * @Autor lzhiqiang
 * @Date 2023-04-05 13:14:51
 * @LastEditors lzhiqiang
 * @LastEditTime 2023-04-05 22:03:43
 */
#include "my_module.h"
#include "chat_servlet.h"
#include "../src/config.h"
#include "../src/log.h"
#include "../src/tcp_server.h"
#include "../src/application.h"
#include "../src/http/servlet.h"
#include "../src/env.h"


namespace chat
{
    static johnsonli::Logger::ptr g_logger = LOG_ROOT();

    MyModule::MyModule()
        :johnsonli::Module("chat-room/1.0") {
    }

     MyModule::~MyModule() {}

    bool MyModule::onLoad() {
        LOG_INFO(g_logger) << "onLoad";
        return true;
    }

    bool MyModule::onUnload() {
        LOG_INFO(g_logger) << "onUnload";
        return true;
    }

    // int32_t handle(johnsonli::http::HttpRequest::ptr request
    //                 , johnsonli::http::HttpResponse::ptr response
    //                 , johnsonli::http::HttpSession::ptr session)
    // {
    //     response->setBody("hello handle");
    //     return 0;
    // }

    bool MyModule::onServerReady() {

        LOG_INFO(g_logger) << "onServerReady";

        std::vector<johnsonli::TcpServer::ptr> svrs;
        if(!johnsonli::Application::GetInstance()->getServer("http", svrs))
        {
            LOG_INFO(g_logger) << "no httpserver alive";
        }

        for(auto& i : svrs)
        {
            johnsonli::http::HttpServer::ptr http_server = 
                std::dynamic_pointer_cast<johnsonli::http::HttpServer>(i);

            if(!http_server)
            {
                continue;
            }

            auto slt_dispatch = http_server->getServletDispatch();

            johnsonli::http::ReSourseServlet::ptr slt(new johnsonli::http::ReSourseServlet(
                johnsonli::EnvMgr::GetInstance()->getCwd() //当前可执行程序所在路径
            ));

            slt_dispatch->addGlobServlet("/html/*", slt);
            LOG_INFO(g_logger) << "addServlet";

        }


        svrs.clear();

        // websocket
        if(!johnsonli::Application::GetInstance()->getServer("ws", svrs))
        {
            LOG_INFO(g_logger) << "no websocket alive";
        }

        for(auto& i : svrs)
        {
            johnsonli::http::WSServer::ptr ws_server = 
                std::dynamic_pointer_cast<johnsonli::http::WSServer>(i);

            if(!ws_server)
            {
                continue;
            }

            johnsonli::http::ServletDispatch::ptr slt_dispatch = ws_server->getWSServletDispatch();

            ChatServlet::ptr slt(new ChatServlet);

            slt_dispatch->addGlobServlet("/sylar/chat", slt);
            LOG_INFO(g_logger) << "addServlet";

        }
        

        return true;
    }

    bool MyModule::onServerUp() {
        LOG_INFO(g_logger) << "onServerUp";
        return true;
    }
}